package cn.wolfcode.luowowo.resolver;

import cn.wolfcode.luowowo.annotation.UserParam;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.RedisService.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求映射方法参数解析器
 *
 * 注入当前对象
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver{
    //注入用户缓存Redis服务接口
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    //指定当前解析器能支持解析的参数类型
    //返回值是true或者false：ture表示支持解析指定参数，false表示不支持指定参数
    //当前登录用户对象：UserInfo
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType()== UserInfo.class&&methodParameter.hasParameterAnnotation(UserParam.class);
    }
    //如果上面的方法返回true是才会执行
    //执行获取当前登录用户信息对象，将返回值注入 请求映射方法声明的UserInfo类型的形式参数中
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取当前登录用户对象，然后返回
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        return user;
    }
}
